//
//  CFHoveringTableViewController.m
//  CFHoveringTableViewDemo
//

//

#import "CFHoveringTableViewController.h"
#import "CFContentTableView.h"
#import "CFTitleBar.h"
#import "NextTableViewController.h"
#import "CFContentScrollView.h"
#import "CFContentHeadView.h"
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#import <Masonry.h>
#import "YLDiscoveryHeader.h"
#import "YLActivityTableViewCell.h"
#import "YLRealNameAuthenticationViewController.h"
#import "YLIntegralMallController.h"
#import "YLMemberController.h"
#import "WHProgressHUD.h"
#import "YLInvitingFriendsController.h"
#import "YLPersonaInformationController.h"
#import "YLMineViewModel.h"
#import "YLAccountTool.h"
#import "YLCertifiedPaymentViewController.h"
#import "YLAdView.h"
#import "YLAdViewModel.h"
#import "YLAdModel.h"
#import "WHWebViewController.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
@interface CFHoveringTableViewController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (nonatomic, weak) CFContentScrollView *scrollView;
@property (nonatomic, weak) CFContentTableView *table1;
@property (nonatomic, weak) CFContentTableView *table2;

@property (nonatomic, strong) UIView *tableViewHeadView;

@property (nonatomic, weak) UIView *headBackView;

@property (nonatomic, weak) CFTitleBar *titleBarView;

@property (nonatomic, assign) CGFloat headViewHeight;
@property (nonatomic, strong) YLAdViewModel *adViewModel;
@end

@implementation CFHoveringTableViewController


- (YLAdViewModel *)adViewModel
{
    if (!_adViewModel) {
        _adViewModel = [[YLAdViewModel alloc] init];
        _adViewModel.conditionId = 13;
    }
    return _adViewModel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"发现";
    
    __weak typeof(self) weakSelf = self;
    [[self.adViewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        YLAdModel *model = x;
        YLAdView *adView = [[YLAdView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        adView.iconUrl = model.noticeIcon;
        [[UIApplication sharedApplication].keyWindow addSubview:adView];
        adView.clickBlock = ^{
            WHWebViewController *webCon = [[WHWebViewController alloc] init];
            [weakSelf.navigationController pushViewController:webCon animated:YES];
        };
    }];
    
    self.view.backgroundColor = YLColor(248, 249, 252);
    
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    
    self.view.clipsToBounds = YES;
    
    self.headViewHeight = HeadViewHeight;
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self setupContentView];
    
    [self setupHeadView];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [WHProgressHUD dismiss];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupContentView
{
    __weak typeof(self) weakSelf = self;
    CFContentScrollView* scrollView = [[CFContentScrollView alloc] init];
    scrollView.backgroundColor = YLColor(248, 249, 252);
    scrollView.delaysContentTouches = NO;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    scrollView.pagingEnabled = YES;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.delegate = self;
    scrollView.contentSize = CGSizeMake(kScreenWidth * 2, 0);
    
    UIView* headView = [[UIView alloc] init];
    headView.frame = CGRectMake(0, 64, 0, self.headViewHeight + TitleHeight);
    self.tableViewHeadView = headView;
    
    CFContentTableView* table1 = [[CFContentTableView alloc] init];
     [table1 registerNib:[UINib nibWithNibName:NSStringFromClass([YLActivityTableViewCell class]) bundle:nil] forCellReuseIdentifier:[YLActivityTableViewCell cellID]];
    
    table1.tag = 1;
    table1.dataSource = self;
    table1.delegate = self;
    self.table1 = table1;
    table1.tableHeaderView = headView;
    [scrollView addSubview:table1];
    [table1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(scrollView);
        make.width.mas_equalTo(kScreenWidth);
        make.top.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view);
    }];
    
    
    CFContentTableView* table2 = [[CFContentTableView alloc] init];
    table2.dataSource = self;
    [table2 registerNib:[UINib nibWithNibName:NSStringFromClass([YLActivityTableViewCell class]) bundle:nil] forCellReuseIdentifier:[YLActivityTableViewCell cellID]];
    table2.tag = 2;
    table2.delegate = self;
    self.table2 = table2;
    table2.tableHeaderView = headView;
    [scrollView addSubview:table2];
    [table2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(scrollView).offset(kScreenWidth);
        make.width.mas_equalTo(table1);
        make.top.bottom.mas_equalTo(table1);
    }];
    
    table1.emptyDataSetSource = self;
    table1.emptyDataSetDelegate = self;
    
    table2.emptyDataSetSource = self;
    table2.emptyDataSetDelegate = self;
    [table1 registerNib:[UINib nibWithNibName:NSStringFromClass([YLActivityTableViewCell class]) bundle:nil] forCellReuseIdentifier:[YLActivityTableViewCell cellID]];
    [table2 registerNib:[UINib nibWithNibName:NSStringFromClass([YLActivityTableViewCell class]) bundle:nil] forCellReuseIdentifier:[YLActivityTableViewCell cellID]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 5;
    }
    return YLScreenW * 325 / 750.0;
    
}


- (void)setupHeadView
{
    
    __weak typeof(self) weakSelf = self;
    UIView* headBackView = [[CFContentHeadView alloc] init];
    headBackView.backgroundColor = [UIColor blueColor];
    headBackView.frame = CGRectMake(0, 0, kScreenWidth, self.headViewHeight + TitleHeight);
    [self.view addSubview:headBackView];
    self.headBackView = headBackView;
    
    YLDiscoveryHeader *header = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YLDiscoveryHeader class]) owner:nil options:nil].lastObject;
    [headBackView addSubview:header];
    
    
    [header.myInfoSingal subscribeNext:^(id  _Nullable x) {
        
        YLAccount *account = [YLAccountTool account];
        if (account.authState == 0) {
            YLCertifiedPaymentViewController *con = [[YLCertifiedPaymentViewController alloc] init];
            [weakSelf.navigationController pushViewController:con animated:YES];
            return ;
        }
        
        YLMineViewModel *viewModel = [[YLMineViewModel alloc] init];
        [[viewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
            YLPersonaInformationController *info = [[YLPersonaInformationController alloc] init];
            info.model = viewModel.myInfoModel;
            [weakSelf.navigationController pushViewController:info animated:YES];
        }];
        
    }];
    
    [header.invitingFriendsSingal subscribeNext:^(id  _Nullable x) {
        
        YLAccount *account = [YLAccountTool account];
        if (account.authState == 0) {
            YLCertifiedPaymentViewController *con = [[YLCertifiedPaymentViewController alloc] init];
            [weakSelf.navigationController pushViewController:con animated:YES];
            return ;
        }
        
        
        YLInvitingFriendsController *inviting = [[YLInvitingFriendsController alloc] init];
        [weakSelf.navigationController pushViewController:inviting animated:YES];
    }];
    
    [header.integralMallSubject subscribeNext:^(id  _Nullable x) {
        YLAccount *account = [YLAccountTool account];
        if (account.authState == 0) {
            YLCertifiedPaymentViewController *con = [[YLCertifiedPaymentViewController alloc] init];
            [weakSelf.navigationController pushViewController:con animated:YES];
            return ;
        }
        
        
        YLIntegralMallController *mall = [[YLIntegralMallController alloc] init];
        [weakSelf.navigationController pushViewController:mall animated:YES];
    }];
    
    
    [header.memberCenterSubject subscribeNext:^(id  _Nullable x) {
        YLAccount *account = [YLAccountTool account];
        if (account.authState == 0) {
            YLCertifiedPaymentViewController *con = [[YLCertifiedPaymentViewController alloc] init];
            [weakSelf.navigationController pushViewController:con animated:YES];
            return ;
        }
        
        YLMemberController *member = [[YLMemberController alloc] init];
        [weakSelf.navigationController pushViewController:member animated:YES];
    }];
    
    [header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(headBackView);
    }];
    
    CFTitleBar* titleBarView = [[CFTitleBar alloc] init];
    
    [headBackView addSubview:titleBarView];
    self.titleBarView = titleBarView;
    titleBarView.backgroundColor = [UIColor whiteColor];
    [titleBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(headBackView);
        make.bottom.mas_equalTo(headBackView.mas_bottom);
        make.height.mas_equalTo(TitleHeight);
    }];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.view);
    }];
    
    titleBarView.titles = @[@" 热门活动 ", @" 往期活动 "];
    titleBarView.selectedIndex = 0;
    titleBarView.buttonSelected = ^(NSInteger index){
        [weakSelf.scrollView setContentOffset:CGPointMake(kScreenWidth * index, 0) animated:YES];
    };
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollView)
    {
        CGFloat contentOffsetX = scrollView.contentOffset.x;
        
        NSInteger pageNum = contentOffsetX / kScreenWidth + 0.5;
        
        self.titleBarView.selectedIndex = pageNum;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollView || !scrollView.window)
    {
        return;
    }
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat originY = 0;
    CGFloat otherOffsetY = 0;
    if (offsetY <= self.headViewHeight)
    {
        originY = -offsetY;
        if (offsetY < 0)
        {
            otherOffsetY = 0;
        }else{
            otherOffsetY = offsetY;
        }
    }else{
        originY = -self.headViewHeight;
        otherOffsetY = self.headViewHeight;
    }
    self.headBackView.frame = CGRectMake(0, originY, kScreenWidth, self.headViewHeight+TitleHeight);
    
    for ( int i = 0; i<self.titleBarView.titles.count; i++ )
    {
        if (i != self.titleBarView.selectedIndex)
        {
            UITableView* contentView = self.scrollView.subviews[i];
            CGPoint offset = CGPointMake(0, otherOffsetY);
            if ([contentView isKindOfClass:[UITableView class]])
            {
                if (contentView.contentOffset.y < self.headViewHeight || offset.y < self.headViewHeight)
                {
                    [contentView setContentOffset:offset animated:NO];
                    self.scrollView.offset = offset;
                }
            }
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString * text = @"暂时还没有相关活动!";
    
    NSDictionary * attributes = @ { NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0f ],
        NSForegroundColorAttributeName:YLColor(130, 130, 130)};
    
    return [[ NSAttributedString  alloc ] initWithString:text attributes:attributes];
}


- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"nodata"];
}

- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
{
    return 25.0f;
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return 40;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"clear"];
        if (!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"contentCell"];
        }
        
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    
    YLActivityTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:[YLActivityTableViewCell cellID]];
  
    return cell;
}

#pragma mark - tableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    YLRealNameAuthenticationViewController * VC = [[YLRealNameAuthenticationViewController alloc] init];
//    [self.navigationController pushViewController:VC animated:YES];
}

- (void)back:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}
@end
